import {EventBusManager} from "../managers/EventBusManager";
import {MidwayConfig} from "../midway";

const EventScope = {
    GlobalBundle: 'global_bundle',
    CurrentBundle: 'current_bundle'
};

const EventType = {
    WebEvent: 'web_event',
    NativeEvent: 'native_event',
    PPTEvent: 'ppt_native_event'
};

class EventBus {
    constructor(webEventBus, nativeEventBus) {
        this._webEventBus = webEventBus;
        this._nativeEventBus = nativeEventBus;
    }

    get WebEventBus() {
        return this._webEventBus;
    }

    addEventListener(name, type, callback, scope = window){
        switch (type) {
            case EventType.WebEvent:
                this._webEventBus.addEventListener(name, callback, scope);
                break;
            case EventType.NativeEvent:
            case EventType.PPTEvent:
                if(this._nativeEventBus) {
                    this._nativeEventBus.registerListener(name, callback, scope);
                }
                break;
            default:
                console.warn('Unsupported event type');
                break;
        }
    }

    removeEventListener(name, type) {
        switch (type) {
            case EventType.WebEvent:
                break;
            case EventType.NativeEvent:
            case EventType.PPTEvent:
                break;
            default:
                console.warn('Unsupported event type');
                break;
        }
    }

    removeAllEventListener() {

    }

    dispatchEvent(name, type, data = {}, eventScope = EventScope.CurrentBundle) {
        //全局广播的事件,只能用于Web事件
        if(eventScope === EventScope.GlobalBundle && type === EventType.WebEvent) {
            EventBusManager.getInstance().broadcast(name, data);
            return -1;
        }
        //处理其他情况
        switch (type) {
            case EventType.WebEvent:
                this._webEventBus.dispatch(name, data);
                return 0;
            case EventType.NativeEvent:
                return this._nativeEventBus.callNative(MidwayConfig.NativeBridgeClass, name, data);
            case EventType.PPTEvent:
                return this._nativeEventBus.callNative(MidwayConfig.NativeBridgeClass, 'sendEvent', {
                    eventName: name,
                    eventData: data
                });
            default:
                console.warn('Unsupported event type');
                break;
        }
    }
}

export {EventBus};